// 引入 API 方法
import { getSupplier } from "@/api/supplier.js";

const state = {
  supplierList: [], // 存储从 JSON 获取的所有用户数据
};

const mutations = {
  SET_SUPPLIER_LIST(state, list) {
    state.supplierList = list;
    localStorage.setItem("vuex-suppliers", JSON.stringify(list)); // 新增本地存储
  },
  ADD_SUPPLIER(state, supplier) {
    state.supplierList.push(supplier);
    localStorage.setItem("vuex-suppliers", JSON.stringify(state.supplierList)); // 新增本地存储
  },
  UPDATE_SUPPLIER(state, updatedSupplier) {
    const index = state.supplierList.findIndex(
      (s) => s.id === updatedSupplier.id
    );
    if (index > -1) {
      state.supplierList.splice(index, 1, updatedSupplier);
      localStorage.setItem(
        "vuex-suppliers",
        JSON.stringify(state.supplierList)
      );
    }
  },
};

const actions = {
  async addSupplier({ commit }, supplier) {
    // 新增 addSupplier action
    commit("ADD_SUPPLIER", supplier);
    return Promise.resolve();
  },
  async loadSupplierList({ commit }) {
    try {
      const localData = localStorage.getItem("vuex-suppliers");
      if (localData) {
        commit("SET_SUPPLIER_LIST", JSON.parse(localData)); // 优先读取本地数据
        return;
      }
      const response = await getSupplier(); // 假设 getUser 返回用户列表
      commit("SET_SUPPLIER_LIST", response.data);
    } catch (error) {
      console.error("加载供应商数据失败:", error);
    }
  },

  // 登录逻辑
  async supplierLogin({ commit, state }, credentials) {
    // 从 supplierList 中匹配用户
    const supplier = state.supplierList.find(
      (s) =>
        s.username === credentials.username &&
        s.password === credentials.password
    );

    if (supplier) {
      commit("SET_LOGIN_PERSON", supplier, { root: true }); // 添加第三个参数
      return Promise.resolve(supplier);
    } else {
      return Promise.reject(new Error("用户名或密码错误"));
    }
  },
  async updateSupplier({ commit }, supplier) {
    commit("UPDATE_SUPPLIER", supplier);
    localStorage.setItem("vuex-suppliers", JSON.stringify(state.supplierList));
    return Promise.resolve();
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
